
package net.qiqbframework.config;



import net.qiqbframework.common.Priority;
import net.qiqbframework.messaging.annotation.FixedValueParameterResolver;
import net.qiqbframework.messaging.annotation.HandlerParameterResolver;
import net.qiqbframework.messaging.annotation.HandlerParameterResolverFactory;

import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;


/**
 * ParameterResolverFactory implementation that resolves parameters from available components in the Configuration
 * instance it was configured with.
 * <p>
 * This implementation is usually auto-configured when using the Configuration API.
 */
@Priority(Integer.MIN_VALUE / 2)
public class ConfigurationParameterResolverFactory implements HandlerParameterResolverFactory {

    private final Configuration configuration;

    /**
     * Initialize an instance using given {@code configuration} to supply the value to resolve parameters with
     *
     * @param configuration The configuration to look for component
     */
    public ConfigurationParameterResolverFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public HandlerParameterResolver<?> createInstance(Executable executable, Parameter[] parameters, int parameterIndex) {
        Object component = configuration.getComponent(parameters[parameterIndex].getType());
        return component == null ? null : new FixedValueParameterResolver<>(component);
    }
}
